﻿using Autofac;
using AutoMapper;
using System.Linq;
using System.Reflection;
using System.Web.Compilation;
using Yz.Core.Base;

namespace Yz.Mvc.Startups
{
    public class StartupAutofac
    {
        /// <summary>
        /// autofac的注入
        /// </summary>
        /// <param name="app"></param>
        public static ContainerBuilder RegisterService()
        {
            //创建autofac管理注册类的容器实例
            var builder = new ContainerBuilder();

            #region 实现接口IDependency 的自动注入
            var baseType = typeof(IDependency);
            var assemblys = BuildManager.GetReferencedAssemblies().Cast<Assembly>().ToList();
            builder.RegisterAssemblyTypes(assemblys.ToArray())
                  .Where(t => baseType.IsAssignableFrom(t) && t != baseType)
                  .PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies).AsImplementedInterfaces().InstancePerLifetimeScope();
            #endregion

            #region autoMapper注入 
            builder.RegisterType<Mapper>()
            .PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies).As<IMapper>()
            .InstancePerLifetimeScope();
            #endregion

            //builder.RegisterControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired(); //生成具体的实例 
            return builder;
        }
    }
}
